package com.skytech.chatim.sky.xmlapi;



import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.util.Log;

import com.skytech.chatim.sky.xmlapi.command.XmlApiCommand;
import com.skytech.chatim.sky.xmlapi.command.XmlApiCommandResult;



/**
 * Created by Vega on 2015/1/7.
 */
public class XmlApiClient {

    private static final String TAG = XmlApiClient.class.getSimpleName();
    private static final String XML_CONTENT_TYPE = "application/xml; charset=ISO-8859-1";

    private String user;
    private String password;
    private String siteName;


    public XmlApiClient(String user, String password, String siteName) {
        this.user = user;
        this.password = password;
        this.siteName = siteName;
    }

    public XmlApiClient(WebexConfig webexConfig) {
        this(webexConfig.getUserName(),webexConfig.getPassword(),webexConfig.getSite());
    }

    private String buildEndPoint() {
        return "https://" + siteName + ".webex.com.cn/WBXService/XMLService";
    }

    public XmlApiCommandResult issueCommand(XmlApiCommand command) {
        try {
            HttpPost request = new HttpPost(buildEndPoint());
            request.setHeader("Content-Type", XML_CONTENT_TYPE);
            XmlApiRequest xmlApiRequest = new XmlApiRequest(user, password, siteName, command);
            String xml = xmlApiRequest.toXML();
            Log.d(TAG, "czqresult xml is {}" + xml);
            request.setEntity(new StringEntity(xml, "UTF-8"));
            HttpParams httpParams = new BasicHttpParams();
            HttpClient client = new DefaultHttpClient(httpParams);
            HttpResponse response = client.execute(request);
            String xmlResponse = EntityUtils.toString(response.getEntity());
            XmlApiCommandResult XmlApiCommandResult = new XmlApiCommandResult(xmlResponse);
            XmlApiCommandResult.parseResponse();
            Log.d(TAG, "czqresult xmlResponse is {}" + xmlResponse);
            return XmlApiCommandResult;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null ;
    }

}
